package com.joysuch.wwyt.bp.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.joysuch.wwyt.bp.bean.risk.BpReportSettingBean;
import com.joysuch.wwyt.bp.bean.risk.BpReportSettingDto;
import com.joysuch.wwyt.bp.bean.risk.BpSafeRiskContentBean;
import com.joysuch.wwyt.bp.bean.risk.BpSpecialWorkTypeBean;
import com.joysuch.wwyt.bp.entity.risk.BpReportSetting;
import com.joysuch.wwyt.bp.entity.risk.BpSafeRiskContent;
import com.joysuch.wwyt.bp.enums.DataStateTypes;
import com.joysuch.wwyt.bp.repository.BpReportSettingRepository;
import com.joysuch.wwyt.bp.repository.BpSafeRiskContentRepository;
import com.joysuch.wwyt.bp.service.BpReportSettingService;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.support.Context;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author ZhangDong
 * @Date 2020/3/3 17:14
 */
@Data
@Slf4j
@Service
@Transactional
public class BpReportSettingServiceImpl implements BpReportSettingService {

    @Autowired
    private BpReportSettingRepository bpReportSettingRepository;
    @Autowired
    private BpSafeRiskContentRepository bpSafeRiskContentRepository;
    @Autowired
    private BaseUserDao baseUserDao;


    @Override
    public ResultBean save(BpReportSettingBean bpReportSettingBean) {
        List<BpSafeRiskContentBean> contentBeans = bpReportSettingBean.getContentBeans();

        //标题相同拦截
        if (!CollectionUtils.isEmpty(contentBeans)) {
            Map<String, Long> collect = contentBeans.stream().collect(Collectors.groupingBy(BpSafeRiskContentBean::getTitle, Collectors.mapping(Function.identity(), Collectors.counting())));
            for (Long value : collect.values()) {
                if (value > 1) {
                    return ResultBean.fail(101, "标题不可重复");
                }
            }
        }
        List<BpReportSetting> all = bpReportSettingRepository.findAll();
        String flag = "新增";  //新增
        if (!CollectionUtils.isEmpty(all)) {
            flag = "修改";
        }
        String currentOrgCode = Context.getCurrentOrgCode();
        log.info("上报配置，orgCode:{},{}表数据:{}", currentOrgCode, flag, JSON.toJSONString(bpReportSettingBean));

        //清表
        bpReportSettingRepository.deleteAll();
        bpSafeRiskContentRepository.deleteAll();

        //存主表
        BpReportSetting bpReportSetting = new BpReportSetting();
        BeanUtils.copyProperties(bpReportSettingBean, bpReportSetting);
        bpReportSetting.setSpecialWorkType(JSON.toJSONString(bpReportSettingBean.getTypeBeanList()));
        bpReportSettingRepository.save(bpReportSetting);

        //存安全风险研判内容
        if (!CollectionUtils.isEmpty(contentBeans)) {
            List<BpSafeRiskContent> riskContents = Lists.newArrayList();
            for (BpSafeRiskContentBean contentBean : contentBeans) {
                String title = contentBean.getTitle();
                List<String> details = contentBean.getDetails();
                if (StringUtils.isEmpty(title.trim())) {
                    return ResultBean.fail(101, "标题不能为空");
                }
                if (CollectionUtils.isEmpty(details)) {
                    return ResultBean.fail(101, "内容不能为空");
                }
                for (String detail : details) {
                    if (StringUtils.isEmpty(detail.trim())) {
                        return ResultBean.fail(101, "内容不能为空");
                    }
                    BpSafeRiskContent bpSafeRiskContent = new BpSafeRiskContent();
                    bpSafeRiskContent.setTitle(title);
                    bpSafeRiskContent.setContent(detail);
                    riskContents.add(bpSafeRiskContent);
                }
            }
            bpSafeRiskContentRepository.saveAll(riskContents);
        }
        return ResultBean.defaultSuccessResult();
    }

    @Override
    public ResultBean getById(Long id) {
        //分页
        if (id == 0) {
            List<BpReportSetting> all = bpReportSettingRepository.findAll();
            if (!CollectionUtils.isEmpty(all)) {
                BpReportSetting bpReportSetting = all.get(0);
                bpReportSetting.setUpdateByName(baseUserDao.getBaseUserNameById(bpReportSetting.getUpdateBy()));
                Optional<BaseUser> byId = baseUserDao.findById(bpReportSetting.getEnterpriseChargerId());
                if (byId.isPresent() && (byId.get().getState() == null || byId.get().getState() != DataStateTypes.DELETE.getState())) {
                    bpReportSetting.setEnterpriseChargerName(byId.get().getRealName());
                } else {
                    bpReportSetting.setEnterpriseChargerName(null);
                    //bpReportSetting.setEnterpriseChargerId(null);
                }
                // bpReportSetting.setEnterpriseChargerName(baseUserDao.getBaseUserNameById(bpReportSetting.getEnterpriseChargerId()));
                return ResultBean.success(bpReportSetting);
            } else {
                return ResultBean.success(null);
            }
        }
        //单体查询+ 班组级等查询
        BpReportSetting bpReportSetting = bpReportSettingRepository.findById(id).orElse(null);
        if (bpReportSetting == null) {
            List<BpReportSetting> all = bpReportSettingRepository.findAll();
            if (CollectionUtils.isEmpty(all)) {
                return ResultBean.success(null);
            } else {
                bpReportSetting = all.get(0);
            }
        }
        BpReportSettingDto dto = new BpReportSettingDto();
        BeanUtils.copyProperties(bpReportSetting, dto);
        //负责人
        dto.setDepartChargerName(baseUserDao.getBaseUserNameById(bpReportSetting.getDepartChargerId()));
        //企业负责人-如果人员已经被删除(state=44)则不显示
        Optional<BaseUser> byId = baseUserDao.findById(bpReportSetting.getEnterpriseChargerId());
        if (byId.isPresent() && byId.get().getState() == DataStateTypes.DELETE.getState()) {
            dto.setEnterpriseChargerName(null);
           // dto.setEnterpriseChargerId(null);
        }
        //dto.setEnterpriseChargerName(baseUserDao.getBaseUserNameById(bpReportSetting.getEnterpriseChargerId()));
        List<BpSafeRiskContent> all = bpSafeRiskContentRepository.findAll();
        Map<String, List<String>> map = all.stream().collect(Collectors.groupingBy(BpSafeRiskContent::getTitle,
                Collectors.mapping(BpSafeRiskContent::getContent, Collectors.toList())));
        //安全风险研判内容集合
        List<BpSafeRiskContentBean> contentBeanList = Lists.newArrayList();
        for (String s : map.keySet()) {
            BpSafeRiskContentBean bpSafeRiskContentBean = new BpSafeRiskContentBean();
            bpSafeRiskContentBean.setTitle(s);
            bpSafeRiskContentBean.setDetails(map.get(s));
            contentBeanList.add(bpSafeRiskContentBean);
        }
        dto.setContentBeanList(contentBeanList);
        //特种作业类别集合
        String specialWorkType = bpReportSetting.getSpecialWorkType();
        List<BpSpecialWorkTypeBean> typeBeans = JSON.parseArray(specialWorkType, BpSpecialWorkTypeBean.class);
        dto.setTypeBeanList(typeBeans);
        return ResultBean.success(dto);
    }
}
